package dtaskboard.client.project;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.corechart.CoreChart;

import dtaskboard.client.Constants;
import dtaskboard.client.charts.ProjectBurnupChart;
import dtaskboard.client.charts.SprintBurndownChart;
import dtaskboard.client.dto.HistoryDTO;
import dtaskboard.client.dto.ProjectDTO;
import dtaskboard.client.dto.SprintDTO;
import dtaskboard.client.dto.TaskDTO;
import dtaskboard.client.project.dialog.CreateHistoryDialog;
import dtaskboard.client.project.widget.HistoryWidget;
import dtaskboard.client.project.widget.TaskWidget;
import dtaskboard.client.service.ProjectService;
import dtaskboard.client.service.ProjectServiceAsync;
import dtaskboard.client.util.OpenDialogButton;

public class ProjectPage {
  private final String projectName;
  private final FlexTable projectTable;


  public ProjectPage(String project) {

    this.projectTable = new FlexTable();
    this.projectTable.addStyleName("projectTable");
    this.projectTable.setBorderWidth(1);

    this.projectName = project;
    Panel mainPanel = RootPanel.get(Constants.mainPanel);
    mainPanel.clear();
    mainPanel.removeStyleName("loginTable");



    this.projectTable.setWidget(0, 0, this.tableHeader("História"));
    this.projectTable.setWidget(0, 1, this.tableHeader("A fazer"));
    this.projectTable.setWidget(0, 2, this.tableHeader("Em progresso"));
    this.projectTable.setWidget(0, 3, this.tableHeader("Verificando"));
    this.projectTable.setWidget(0, 4, this.tableHeader("Feito"));

    String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
    ProjectServiceAsync projectService = GWT.create(ProjectService.class);
    projectService.getLatestSprint(this.projectName, sessionId,
        new AsyncCallback<SprintDTO>() {

          @Override
          public void onSuccess(SprintDTO result) {
            Panel mainPanel = RootPanel.get(Constants.mainPanel);
            mainPanel.add(ProjectPage.this.projectTable);


            mainPanel.add(new OpenDialogButton("Criar história",
                new CreateHistoryDialog(ProjectPage.this.projectName)));
            ProjectPage.this.fillTable(result);
            ProjectPage.this.addBurndown(result);
            ProjectPage.this.addProjectBurnup();
          }

          @Override
          public void onFailure(Throwable caught) {
            Panel mainPanel = RootPanel.get(Constants.mainPanel);
            mainPanel.add(new Label("Não há sprint ativo."));
          }
        });
  }

  private void addBurndown(final SprintDTO sprint) {
    Runnable onLoadCallback = new Runnable() {
      @Override
      public void run() {
        Panel mainPanel = RootPanel.get(Constants.mainPanel);
        mainPanel.add(SprintBurndownChart.build(sprint));
      }
    };

    VisualizationUtils.loadVisualizationApi(onLoadCallback, CoreChart.PACKAGE);
  }

  private void addProjectBurnup() {
    ProjectServiceAsync projectService = GWT.create(ProjectService.class);

    String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
    projectService.getProject(this.projectName, sessionId,
        new AsyncCallback<ProjectDTO>() {

          @Override
          public void onSuccess(final ProjectDTO project) {
            Runnable onLoadCallback = new Runnable() {
              @Override
              public void run() {
                Panel mainPanel = RootPanel.get(Constants.mainPanel);
                mainPanel.add(ProjectBurnupChart.build(project));
              }
            };

            VisualizationUtils.loadVisualizationApi(onLoadCallback,
                CoreChart.PACKAGE);
          }

          @Override
          public void onFailure(Throwable caught) {
            // TODO Auto-generated method stub

          }
        });
  }

  private void fillTable(SprintDTO sprint) {
    int numSprints = sprint.getHistories().size();
    for (int i = 0; i < numSprints; i++) {
      HistoryDTO history = sprint.getHistories().get(i);
      int row = i + 1;
      this.projectTable.setWidget(row, 0, new HistoryWidget(this.projectName,
          history));

      for (int j = 1; j < 5; j++) {
        this.projectTable.setWidget(row, j, new FlowPanel());
      }

      for (TaskDTO task : history.getTasks()) {
        this.addTaskToTable(task, row);
      }

    }
  }

  private void addTaskToTable(TaskDTO task, int row) {
    int column = 1;
    switch (task.getStatus()) {
      case TODO:
        column = 1;
        break;
      case DOING:
        column = 2;
        break;
      case VERIFY:
        column = 3;
        break;
      case DONE:
        column = 4;
        break;
    }
    Panel panel;
    if (this.projectTable.isCellPresent(row, column)) {
      panel = (Panel) this.projectTable.getWidget(row, column);
    } else {
      panel = new FlowPanel();
      this.projectTable.setWidget(row, column, panel);
    }
    panel.add(new TaskWidget(this.projectName, task));
  }

  private Label tableHeader(String title) {
    Label label = new Label(title);
    label.addStyleName("tableHeader");
    return label;
  }

}
